﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GoogleServicesLib.GeoCoding;
using GoogleServicesLib;
using System.Collections;
using System.Threading;

namespace GMapWithBingControl
{
    public partial class SearchCtr : UserControl
    {
        public GeocodingResult SelectedResult { get; private set; }
        private GeocodingResult[] _results;

        public SearchCtr()
        {
            InitializeComponent();
            this.txtSearch.ItemsSource = new string[] { "hanoi, vietnam", "ha nam", "hai duong" };
        }

        private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {

            }
            else
            {

            }
        }

        private void txtSearch_LostFocus(object sender, RoutedEventArgs e)
        {
            //this.Visibility = Visibility.Collapsed;
        }

        public void TakeFocus()
        {
            this.txtSearch.Focus();
        }

        private async void SearchLocation(string txt, bool sensor)
        {
            GeocodingRequest request = new GeocodingRequest();
            request.Address = txt;
            request.Sensor = sensor.ToString().ToLower();

            GeocodingResponse response = await GeocodingService.GetResponse(request);

            if (response.Status == ResponseStatus.Ok)
                this._results = response.Results;
            else
                this._results = null;
            //this.txtSearch.ItemsSource = ConvertToString(this._results);
        }

        private string[] ConvertToString(GeocodingResult[] result)
        {
            List<string> list = new List<string>();
            foreach (GeocodingResult r in result)
            {
                list.Add(r.FormattedAddress);
            }
            return list.ToArray();
        }

        private void txtSearch_TextChanged(object sender, RoutedEventArgs e)
        {

        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            string strSearch = this.txtSearch.Text + e.Key.ToString();
            SearchLocation(strSearch, false);
        }

        private void txtSearch_TextInputStart(object sender, TextCompositionEventArgs e)
        {
            MessageBox.Show(this.txtSearch.Text);
        }

        private void txtSearch_TextInput(object sender, TextCompositionEventArgs e)
        {
            MessageBox.Show(this.txtSearch.Text);
        }

    }
}
